package com.vincent.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by wensen on 2016/12/7.
 *
 * A process is a thread with a queue of incoming messages, and an
 *  "environment" that keeps track of all processes and queues.
 */
public abstract class Process implements Runnable{

    private static Logger LOGGER = LoggerFactory.getLogger(Process.class);

    private Environment env;
    private int id;
    private BlockingQueue<Message> inBox;
    public Process(Environment env, int id) {
        this.env = env;
        this.id = id;
        inBox = new LinkedBlockingQueue<Message>();
    }

    public void run() {

        try {
            this.body();
            this.env.removeProc(this.id);
        } catch (Exception e) {

        }
    }

    public Message getNextMessage() throws InterruptedException{
        return inBox.take();
    }

    public void sendMessage(int dst, Message msg) {
        this.env.sendMessage(dst, msg);
    }

    public void deliver(Message msg) {

        this.inBox.add(msg);
        LOGGER.debug("deliver message");
    }

    public int id() {
        return this.id;
    }

    public Environment env() {
        return this.env;
    }

    protected void addProc(Process prc) {
        this.env.addProc(prc);
    }
    //
    public abstract void body();

}
